package manager.data;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import manager.utility.PacketParser;

import static manager.utility.StaticFields.*;

public class UDPServer extends Thread {

	private LazyPersistedQueue lpq;
	private EventsManager em;
	private DatagramSocket serverSocket;
	private byte[] receiveData;
	private static PacketParser pp;
	
	public UDPServer(LazyPersistedQueue lpq, EventsManager em) {
		pp = PacketParser.getInstance();
		this.lpq= lpq;
		this.em = em;		
	}

	public void run() {
		receiveData = new byte[UDP_PACK_SIZE];
		try {		
			serverSocket = new DatagramSocket(UDP_PORT);
			while(true)
			{
				DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
				serverSocket.receive(receivePacket);
				byte[] b = receivePacket.getData();
					RawDataObject rdo = pp.create(b);
					if(rdo!=null){
						System.out.println("receive packet...");
						lpq.enqueue(rdo);
						em.processEvents();
					}
			}
			} catch (SocketException e) {
				if(serverSocket!=null)
					if(!serverSocket.isClosed())
						serverSocket.close();
			} catch (IOException e) {
				if(serverSocket!=null)
					if(!serverSocket.isClosed())
						serverSocket.close();
			}
	}


	
	public void closeSocket(){
		if(serverSocket!=null)
			if(!serverSocket.isClosed())
				serverSocket.close();
	}
	
}
